package br.com.banco.control;

import br.com.banco.Extrato;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ConsultaExtratoPeriodo
 */
public class ConsultaExtratoPorPeriodo extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ConsultaExtratoPorPeriodo() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        Date inicio = null, fim = null;
        try {
            final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
            inicio = format.parse(request.getParameter("dtInicio"));
            fim = format.parse(request.getParameter("dtFim"));
        } catch (ParseException e) {
            request.setAttribute("erros", "Esse formato de data é inválido.");
            request.getRequestDispatcher("menuOpcoes.jsp").forward(request, response);
        }

        Extrato extrato = new Extrato().consultaPorPeriodo(inicio, fim);
        if (extrato == null) {
            response.sendRedirect("menuOpcoes.jsp");
        } else {
            request.setAttribute("extrato", extrato);
            request.getRequestDispatcher("extrato.jsp").forward(request,
                    response);
        }

    }
}
